import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import (
    QWidget,
    QPushButton,
    QApplication,
    QMainWindow,
    QFileDialog,
    QMessageBox,
    QAction,
    QColorDialog,
)
from PyQt5.QtGui import QGuiApplication, QColor, QIcon, QPainter, QKeySequence, QFont
from PyQt5.QtPrintSupport import QPrintDialog, QPrinter
from PyQt5.QtCore import pyqtSlot, Qt, QPoint


class MyCanvas(QWidget):
    def __init__(self):
        super().__init__()
        self.setMouseTracking(True)
        self.curr = QPoint(0, 0)
        self.drawing = False
        self.lines = []  # Store all line segments
        self.color = Qt.GlobalColor.blue

    def mousePressEvent(self, a0):
        print(a0.pos())
        self.curr = a0.pos()
        self.drawing = True

    def mouseMoveEvent(self, a0):
        if self.drawing:
            print(f"current mouse at: {a0.pos()}")
            # Store the line segment
            # print(self.drawing)
            self.lines.append((self.curr, a0.pos()))
            # Update current position for next line segment
            self.curr = a0.pos()
            # Trigger repaint
            self.update()

    def mouseReleaseEvent(self, a0):
        self.drawing = False

    def paintEvent(self, event):
        super().paintEvent(event)
        painter = QPainter(self)
        painter.setRenderHint(QPainter.RenderHint.Antialiasing)
        painter.setPen(self.color)

        # Draw all stored line segments
        for start, end in self.lines:
            painter.drawLine(start, end)

    def open_plaette(self):
        self.colordialog = QColorDialog()
        selected_color = self.colordialog.getColor().name()
        print(selected_color)
        self.color = QColor(selected_color)


class MyMainWindow(QMainWindow):
    open_file_name = ""

    def __init__(self):
        super().__init__()
        screen_geometry = QGuiApplication.primaryScreen().geometry()
        screen_width = screen_geometry.width()
        screen_height = screen_geometry.height()
        # Example: Center the window
        self.width = 800
        self.height = 540
        # self.setFixedSize(self.width, self.height)
        self.left = (screen_width - self.width) // 2
        self.top = (screen_height - self.height) // 2
        self.initUI()

    def initUI(self):
        self.setWindowTitle("LittleBird")
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.statusBar().showMessage("Ready")
        self.text_edit = QtWidgets.QTextEdit()
        self.text_edit.setFocusPolicy(Qt.ClickFocus)
        self.canva = MyCanvas()
        self.setCentralWidget(self.canva)
        # 菜单

        menubar = self.menuBar()
        file_menu = menubar.addMenu("File")
        edit_menu = menubar.addMenu("Edit")
        # Remember to set the tool tip for the file menu, otherwise it will not be displayed
        file_menu.setToolTipsVisible(True)

        exit_action = QAction("Exit", self)
        exit_action.triggered.connect(self.close)
        exit_action.setShortcut("Ctrl+Q")  # Set shortcut for the exit action
        exit_action.setIcon(QIcon("exit.png"))  # Set icon for the exit action

        print_action = QAction("Print", self)
        # print_action.triggered.connect(lambda: print("Printing..."))
        print_action.triggered.connect(self.print_document)
        print_action.setShortcut("Ctrl+P")  # Set shortcut for the print action
        print_action.setStatusTip(
            "Print the document"
        )  # Set status tip for the print action
        print_action.setToolTip(
            "Print the document"
        )  # Set tool tip for the print action
        print_action.setIcon(QIcon("printer.png"))  # Set icon for the print action

        open_action = QAction("Open", self)
        open_action.triggered.connect(self.open_file)
        open_action.setIcon(QIcon("open-file.png"))  # Set shortcut for the open action
        open_action.setShortcut("Ctrl+O")  # Set shortcut for the open action

        save_action = QAction("Save", self)
        save_action.triggered.connect(self.save_file)
        save_action.setIcon(QIcon("save-file.png"))  # Set shortcut for the save action
        save_action.setShortcut("Ctrl+S")  # Set shortcut for the save action

        undo_action = QAction("Undo", self)
        undo_action.triggered.connect(self.text_edit.undo)
        undo_action.setShortcut("Ctrl+Y")  # Set shortcut for the redo action

        font_inc_action = QAction("Font +", self)
        font_inc_action.triggered.connect(self.increase_font)

        palette_action = QAction("palette", self)
        palette_action.setIcon(QIcon("paint.png"))
        palette_action.triggered.connect(self.canva.open_plaette)

        file_menu.addAction(print_action)
        file_menu.addAction(save_action)
        file_menu.addAction(exit_action)
        edit_menu.addAction(undo_action)
        edit_menu.addAction(font_inc_action)
        # 工具栏
        toolbar = self.addToolBar("Tool")

        toolbar.addAction(print_action)
        toolbar.addAction(open_action)
        toolbar.addAction(save_action)
        toolbar.addAction(exit_action)
        toolbar.addAction(palette_action)

        self.text_edit.focusInEvent = lambda event: print("enter text edit")

        self.show()

    def print_document(self):
        printer = QPrinter()
        # printer.setResolution(300)  # Set resolution to 300 DPI
        dialog = QPrintDialog(printer, self)

        if dialog.exec_() == QPrintDialog.Accepted:
            # If the user accepts the print dialog, render the content
            # Bug fix: Use print_() instead of print()
            self.text_edit.document().print_(printer)

    def open_file(self):
        fname = QFileDialog.getOpenFileName(self, "Open File")
        if fname[0]:
            print("选择了文件：", fname[0])
            self.open_file_name = fname[0]
            with open(fname[0], "r", encoding="utf-8") as f:
                content = f.read()
                self.text_edit.setPlainText(
                    content
                )  # Display the content of the file in QTextEdi

    def save_file(self):
        if self.open_file_name:
            with open(self.open_file_name, "w", encoding="utf-8") as f:
                content = self.text_edit.toPlainText()  # Get the content from QTextEdit
                f.write(content)  # Write the content to the file
        else:
            fname = QFileDialog.getSaveFileName(self, "保存文件")
            if fname[0]:
                print("选择了文件：", fname[0])
                self.open_file_name = fname[0]
                with open(fname[0], "w", encoding="utf-8") as f:
                    content = (
                        self.text_edit.toPlainText()
                    )  # Get the content from QTextEdit
                    f.write(content)  # Write the content to the file
        self.statusBar().showMessage(
            f"{self.open_file_name} 文件已保存"
        )  # Show a message in the status bar

    def closeEvent(self, event):
        reply = QMessageBox.question(
            self,
            "Message",
            "Are you sure to quit?",
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No,
        )

        if reply == QMessageBox.StandardButton.Yes:
            event.accept()
        else:
            event.ignore()

    # def mousePressEvent(self, a0):
    #     if a0.button() == Qt.MouseButton.LeftButton:
    #         QMessageBox.information(self, "Mouse Click", f"Clicked at: {a0.pos()}")

    def increase_font(self):
        old_font_size = self.text_edit.fontInfo().pointSize()
        font = QFont()
        font.setPointSize(old_font_size + 2)
        self.text_edit.setFont(font)


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    app.setWindowIcon(QIcon("icons.png"))
    ex = MyMainWindow()
    sys.exit(app.exec_())
